#!/bin/bash

# 设置环境变量，确保需要root权限的命令使用sudo
SUDO=$(which sudo)

# 更新yum源和配置docker容器
$SUDO yum install -y git || { echo "Failed to install git"; exit 1; }
cd /app/pro/cz-23yw || { echo "Failed to cd into /app/pro/cz-23yw"; exit 1; }
git pull || { echo "Failed to git pull"; exit 1; }
$SUDO sh /app/pro/cz-23yw/sh/run.sh || { echo "Failed to run run.sh"; exit 1; }

# 创建目录并切换到该目录
if [ ! -d "/app/LIUJUE_myz" ]; then
    mkdir -p /app/LIUJUE_myz
fi
cd /app/LIUJUE_myz || { echo "Failed to cd into /app/LIUJUE_myz"; exit 1; }

# 获取git仓库内容
git clone https://gitee.com/ma-yi_zhao/liujuemyz.git || { echo "Failed to clone liujuemyz.git"; exit 1; }

# 创建node目录并复制文件
if [ ! -d "/app/node/app" ]; then
    mkdir -p /app/node/app
fi
if [ -d "/app/LIUJUE_myz/liujuemyz" ]; then
    cp -r /app/LIUJUE_myz/liujuemyz /app/node/app
else
    echo "Source directory /app/LIUJUE_myz/liujuemyz does not exist."
    exit 1
fi

# 切换npm镜像源
docker exec -i node sh -c "npm config set registry http://registry.npm.taobao.org/" || { echo "Failed to set npm registry"; exit 1; }

# 进入node容器并安装依赖
docker exec -it node bash <<'EOF'
cd /app/liujuemyz
npm i || { echo "Failed to install npm packages"; exit 1; }
nohup npm run dev &
EOF

# 将配置信息写入nginx配置文件
if [ -f "/app/nginx/default.conf" ]; then
    $SUDO mv /app/nginx/default.conf /app/nginx/default.conf.bak
fi
cat > /app/nginx/default.conf <<'EOF'
server {
    listen       81;
    listen  [::]:81;
    server_name  localhost;

    location / {
        proxy_pass http://192.168.5.105:8080/;
        proxy_set_header Host $host:$server_port;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}
EOF

# 重启nginx并检查容器状态
$SUDO docker restart nginx || { echo "Failed to restart nginx"; exit 1; }
docker ps -a
